package sh_goods

import (
	"gitee.com/theegg/go-brick/app/model"
	"gitee.com/theegg/go-brick/app/model/system/system_images"
	"gitee.com/theegg/go-brick/app/model/user/users"
	"gitee.com/theegg/go-brick/app/service/app"
	"gitee.com/theegg/go-brick/app/service/help/chtml"
	"gitee.com/theegg/go-brick/app/service/help/cslice"
	"gitee.com/theegg/go-brick/app/service/help/ctime"
	"strings"
	"time"
)

// 查询参数
type QueryParams struct {
	PageSize   string `form:"page_size"  binding:"gte=0,lte=100" label:"每页数量"`
	PageIndex  string `form:"page_index"  binding:"gte=0,lte=99999" label:"当前页数"`
	Username   string `form:"username"  binding:"omitempty,customPlainText=4 32" label:"用户名"`
	Type       string `form:"type"  binding:"omitempty,oneof=0 1 2" label:"类型"`
	GoodsTitle string `form:"goods_title"  binding:"omitempty,customPlainText=4 32" label:"标题"`
}

// 添加参数
type AddParams struct {
	Id           int64  `form:"id" binding:"" label:"ID"`
	SellerId     int64  `form:"seller_id"  binding:"required" label:"卖家ID"`
	GoodsTitle   string `form:"goods_title"  binding:"required,customPlainText=6 64" label:"物品名称"`
	GoodsDesc    string `form:"goods_desc"  binding:"required,customPlainText=2 2048" label:"物品描述"`
	DistrictId   int    `form:"district_id"  binding:"required,gte=1,lte=99999999" label:"所在地"`
	CatId        int    `form:"cat_id"  binding:"required,gte=1,lte=99999" label:"分类"`
	TypeId       int    `form:"type_id"  binding:"required,oneof=1 2" label:"分类"`
	CurrencyUint int    `form:"currency_unit"  binding:"required,oneof=1 2 3" label:"货币单位"`
	BoughtPrice  int64  `form:"bought_price"  binding:"required,gte=0,lte=999999" label:"市场价"`
	SalePrice    int64  `form:"sale_price"  binding:"required,gte=0,lte=999999" label:"卖价"`
	ImageCover   string `form:"image_cover"  binding:"required,customUploadImage=sh/goods" label:"封面图像"`
	ImageList    string `form:"image_list"  binding:"required,customUploadImage=sh/goods m" label:"图像列表"`
	BoughtTime   string `form:"bought_time"  binding:"required" label:"购买时间"`
}

// 类型
var TypeOptions = map[int]string{
	1: "出售",
	2: "求购",
}

// 货币单位
var CurrencyUnitOptions = map[int]string{
	1: "RMB",
	2: "USD",
	3: "VND",
	4: "PESO",
}

// join数据类型
type JoinSecondhandGoodsUser struct {
	SecondhandGoods `xorm:"extends"`
	Username        string
}

// 分页获取所有数据
// @param params map 参数
// @return interface{}, error
func GetDataList(params map[string]interface{}) (map[string]interface{}, error) {
	returnData := make(map[string]interface{}, 0)

	queryParams, errBuild := model.BuildAdminQueryParam(params)
	if errBuild != nil {
		return nil, app.NewError(errBuild)
	}

	query := app.Db().Desc("secondhand_goods.id").Join("LEFT", "users", "secondhand_goods.seller_id = users.id").
		Limit(queryParams.Limit, queryParams.Offset)

	// query cat_id
	if _, ok := queryParams.Params["cat_id"]; ok && queryParams.Params["cat_id"] != "" {
		query.Where("secondhand_goods.cat_id = ?", queryParams.Params["cat_id"])
	}

	// query type
	if _, ok := queryParams.Params["type_id"]; ok && queryParams.Params["type_id"] != "" {
		query.Where("secondhand_goods.type_id = ?", queryParams.Params["type_id"])
	}

	// query district_id
	if _, ok := queryParams.Params["district_id"]; ok && queryParams.Params["district_id"] != "" {
		query.Where("secondhand_goods.district_id = ?", queryParams.Params["district_id"])
	}

	// query goods_title
	if _, ok := queryParams.Params["goods_title"]; ok && queryParams.Params["goods_title"] != "" {
		query.Where("secondhand_goods.goods_title like ?", "%"+queryParams.Params["goods_title"].(string)+"%")
	}

	data := make([]JoinSecondhandGoodsUser, 0)
	// 求总条数
	total, err := query.FindAndCount(&data)
	if err != nil {
		return nil, app.NewError(err)
	}

	for i, v := range data {
		data[i].CatName = SecondhandGoodsCategory[v.CatId]["label"].(string)
		data[i].DistrictName = GetDistrictName(data[i].DistrictId)
		data[i].BoughtTimeStr = time.Unix(data[i].BoughtTime, 0).Format("2006-01-02 00:00:00")
		data[i].ImageCoverUrl = app.GetImageStaticUrl(data[i].ImageCover)

		imageList := strings.Split(v.ImageList, ",")
		imageListArr := make([]map[string]interface{}, 0)
		for ii, vv := range imageList {
			if vv != "" {
				imageListArr = append(imageListArr, map[string]interface{}{
					"id":         ii,
					"image_name": vv,
					"url":        app.GetImageStaticUrl(vv),
				})
			}
		}

		data[i].ImageListArr = imageListArr
	}

	returnData["data"] = data
	returnData["total"] = total

	return returnData, nil
}

// @title AddOrUpdate
// @description 更新或者添加
func (shg *SecondhandGoods) AddOrUpdate(params AddParams, user *users.Users) error {

	imageChangeList := map[string][]string{
		"add": make([]string, 0),
		"del": make([]string, 0),
	}

	// 1. 图片集合拆解
	imageList := make([]string, 0)
	for _, v := range strings.Split(params.ImageList, ",") {
		if v != "" {
			imageList = append(imageList, v)
		}
	}

	// 2. 整理图片变更
	if shg.Id > 0 {
		if shg.ImageList != "" {
			imageOldList := strings.Split(shg.ImageList, ",")
			if len(imageOldList) > 0 {
				imageChangeList["del"] = append(imageChangeList["del"], cslice.StringSliceMainDiff(imageOldList, imageList)...)
			}
		}

		if shg.ImageCover != params.ImageCover {
			imageChangeList["add"] = append(imageChangeList["add"], params.ImageCover)
			if shg.ImageCover != "" {
				imageChangeList["del"] = append(imageChangeList["del"], shg.ImageCover)
			}
		}
	} else {
		imageChangeList["add"] = imageList
		if params.ImageCover != "" {
			imageChangeList["add"] = append(imageChangeList["add"], params.ImageCover)
		}
	}

	shg.SellerId = user.Id
	shg.GoodsTitle = chtml.HtmlPlainText(params.GoodsTitle)
	shg.GoodsDesc = chtml.HtmlPlainText(params.GoodsDesc)

	shg.TypeId = params.TypeId

	shg.DistrictId = params.DistrictId
	shg.CatId = params.CatId

	shg.BoughtPrice = params.BoughtPrice
	shg.SalePrice = params.SalePrice
	shg.CurrencyUint = params.CurrencyUint

	shg.ImageCover = params.ImageCover
	shg.ImageList = params.ImageList

	intTime, _ := ctime.StrTimeToInt64(params.BoughtTime)
	shg.BoughtTime = intTime

	// 3. 开启事务 插入数据
	session := app.Db().NewSession()
	defer session.Close()
	if errSession := session.Begin(); errSession != nil {
		return app.NewError(errSession)
	}

	if shg != nil && shg.Id > 0 {
		affected, errUpdate := session.ID(shg.Id).Update(shg)

		if errUpdate != nil {
			session.Rollback()
			return app.NewError(errUpdate)
		}

		if affected != 1 {
			session.Rollback()
			return app.NewError("更新错误")
		}
	} else {

		affected, errInsert := session.Insert(shg)
		if errInsert != nil {
			session.Rollback()
			return app.NewError(errInsert)
		}

		if affected != 1 {
			session.Rollback()
			return app.NewError("新增内容分类错误(0x001)")
		}
	}

	// 图片处理
	errImage := system_images.ProcessItemImage(shg.Id, imageChangeList)
	if errImage != nil {
		session.Rollback()
		return app.NewError(errImage)
	}

	// 提交
	errCommit := session.Commit()
	if errCommit != nil {
		return app.NewError(errCommit)
	}

	return nil
}

// @title ModifyStatus
// @description 修改管理员状态
func (shg *SecondhandGoods) ModifyStatus() (bool, error) {
	if shg.Status == -1 {
		return false, app.NewError("对不起, 当前内容已经被删除!")
	}

	status := 1
	if shg.Status == 1 {
		status = 0
	}

	affected, err := app.Db().Table(new(SecondhandGoods)).ID(shg.Id).Cols("status").Update(map[string]int{"status": status})

	if err != nil {
		return false, app.NewError(err)
	}

	// 生效条数
	if affected == 0 {
		return false, app.NewError("对不起, 指定的ID更新数量不正确")
	}

	return true, nil
}

// 获取单个数据
// @param id int64 数据的id
// @return *Goods, error
func GetItemById(id int64) (*SecondhandGoods, error) {
	item := new(SecondhandGoods)
	has, err := app.Db().Where("id = ?", id).Get(item)

	if err != nil {
		return nil, err
	}

	if !has {
		return nil, app.NewError("对不起, 目标对象不存在")
	}

	return item, nil
}

// @title TableName
// @description join 数据类型必须返回一个主表的　表名
func (JoinSecondhandGoodsUser) TableName() string {
	return "secondhand_goods"
}
